<template>
	<div class="mobile-editor">
		<Header :changeMode="changeMode" @getData="getData" />

		<div class="content" ref="contentRef" @touchstart="handleClickBlankArea()">
			<div class="viewport-wrapper" :style="viewportStyles">
				<div class="background" :style="backgroundStyle"></div>
				<AlignmentLine v-for="(line, index) in alignmentLines" :key="index" :type="line.type" :axis="line.axis"
					:length="line.length" :canvasScale="canvasScale" />
				<template v-for="element in elementList" :key="element.id">
					<MobileOperate v-if="element.type !== 'line'" :elementInfo="element"
						:isSelected="activeElementIdList.includes(element.id)" :canvasScale="canvasScale"
						:scaleElement="scaleElement" :rotateElement="rotateElement" />
				</template>

				<div class="viewport" ref="viewportRef" :style="{ transform: `scale(${canvasScale})` }">
					<MobileEditableElement v-for="(element, index) in elementList" :key="element.id"
						:elementInfo="element" :elementIndex="index + 1" :selectElement="selectElement" />
				</div>
			</div>
		</div>

		<SlideToolbar />
		<ElementToolbar v-if="handleElement" />

		<div class="operationText" v-for="(element, index) in textElements" :key="index">
			<!-- <div class="operationText_item" v-if="element.">{{ element.content2 }}</div> -->
			<!-- <div class="operationText_item">{{ element.content2 }}</div> -->
		</div>
	</div>
	<FullscreenSpin :loading="exportingCtrl" tip="正在保存..." />
</template>

<script lang="ts" setup>
import FullscreenSpin from "@/components/FullscreenSpin.vue";
let exportingCtrl = ref(false)
import * as cheerio from "cheerio";
import { computed, onMounted, ref, watchEffect } from "vue";
import { storeToRefs } from "pinia";
import { useMainStore, useSlidesStore } from "@/store";
import type { PPTElement } from "@/types/slides";
import type { AlignmentLineProps } from "@/types/edit";
import type { Mode } from "@/types/mobile";
import { VIEWPORT_SIZE } from "@/configs/canvas";
import useSlideBackgroundStyle from "@/hooks/useSlideBackgroundStyle";
import useDragElement from "@/views/Editor/Canvas/hooks/useDragElement";
import useScaleElement from "@/views/Editor/Canvas/hooks/useScaleElement";
import useRotateElement from "@/views/Editor/Canvas/hooks/useRotateElement";

import AlignmentLine from "@/views/Editor/Canvas/AlignmentLine.vue";
import MobileEditableElement from "./MobileEditableElement.vue";
import MobileOperate from "./MobileOperate.vue";
import SlideToolbar from "./SlideToolbar.vue";
import ElementToolbar from "./ElementToolbar.vue";
import Header from "./Header.vue";
import type { index } from "node_modules/cheerio/lib/esm/api/traversing";

import { preservationWorks } from '@/http/api';
import { decryptPpt } from "@/utils/crypto"
import type { ApiResponse } from '@/http/api'; // 使用 type-only import
const data = ref<ApiResponse | null>(null);


defineProps<{
	changeMode: (mode: Mode) => void;
}>();

const getData = (val: boolean) => {
	console.log(val, '222222222')
	exportingCtrl.value = val
}

const slidesStore = useSlidesStore();
const mainStore = useMainStore();
const { slideIndex, currentSlide, viewportRatio } = storeToRefs(slidesStore);
const { activeElementIdList, handleElement } = storeToRefs(mainStore);

const contentRef = ref<HTMLElement>();
const viewportRef = ref<HTMLElement>();

const alignmentLines = ref<AlignmentLineProps[]>([]);

const background = computed(() => currentSlide.value.background);
const { backgroundStyle } = useSlideBackgroundStyle(background);

const canvasScale = computed(() => {
	if (!contentRef.value) return 1;
	const contentWidth = contentRef.value.clientWidth;
	const contentheight = contentRef.value.clientHeight;

	const contentRatio = contentheight / contentWidth;
	if (contentRatio >= viewportRatio.value)
		return (contentWidth - 20) / VIEWPORT_SIZE;
	return (contentheight - 20) / viewportRatio.value / VIEWPORT_SIZE;
});

onMounted(() => {
	if (activeElementIdList.value.length) mainStore.setActiveElementIdList([]);
	if (slideIndex.value !== 0) slidesStore.updateSlideIndex(0);
});

const viewportStyles = computed(() => ({
	width: VIEWPORT_SIZE * canvasScale.value + "px",
	height: VIEWPORT_SIZE * viewportRatio.value * canvasScale.value + "px",
}));

function extractTextFromHTML(html: string): string {
	const div = document.createElement("div");
	div.innerHTML = html;
	return div.innerText || div.textContent || "";
}

const elementList = ref<PPTElement[]>([]);

const textElements = ref<PPTElement[]>([]);
const setLocalElementList = () => {
	elementList.value = currentSlide.value
		? JSON.parse(JSON.stringify(currentSlide.value.elements))
		: [];
	// console.log(JSON.stringify(elementList.value), "值");

	// textElements.value = elementList.value.filter(
	// 	(element) => element.type === "text"
	// );

	// console.log(textElements.value[0].content, "textElements=========");

	textElements.value = elementList.value
		.filter((element) => element.type === "text")
		.map((element) => ({
			...element,
			content2: element.content ? extractTextFromHTML(element.content) : "",
		}));

	console.log(textElements);
};
watchEffect(setLocalElementList);

const { dragElement } = useDragElement(
	elementList,
	alignmentLines,
	canvasScale
);
const { scaleElement } = useScaleElement(
	elementList,
	alignmentLines,
	canvasScale
);
const { rotateElement } = useRotateElement(
	elementList,
	viewportRef,
	canvasScale
);

const selectElement = (
	e: TouchEvent,
	element: PPTElement,
	startMove = true
) => {
	if (!activeElementIdList.value.includes(element.id)) {
		mainStore.setActiveElementIdList([element.id]);
		mainStore.setHandleElementId(element.id);
	}
	if (startMove) dragElement(e, element);
};

const handleClickBlankArea = () => {
	mainStore.setActiveElementIdList([]);
};
</script>

<style lang="scss" scoped>
.operationText {
	width: 100%;

	.operationText_item {
		width: 95%;
		background: #F5F8FF;
		border-radius: 6px;
		margin: auto;
		margin-top: 20px;
		padding: 10px 14px;

		font-family: PingFang SC;
		font-weight: 500;
		font-size: 14px;
		color: #333333;
	}
}

.mobile-editor {
	height: 100%;
	position: relative;
	background-color: $lightGray;
}

.content {
	height: calc(100% - 280px);
	display: flex;
	justify-content: center;
	align-items: center;
}

.viewport {
	transform-origin: 0 0;
}

.viewport-wrapper {
	position: relative;
	box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.1);
}

.background {
	width: 100%;
	height: 100%;
	background-position: center;
	position: absolute;
}

.page {
	background-color: #ffffff;
}
</style>
